var prefix = jsctx + "/tenant/role";

var tenantRole = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageTenantRole",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            roleName: $('#roleName').val().trim()

                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'roleName', title: '角色名称', width: '150', align: 'left'},
                        {field: 'remarks', title: '说明', width: '250', align: 'left'},
                        {
                            field: 'status', title: '状态', width: '250', align: 'left',
                            formatter: function (value, row, index) {

                                if (value == '0') {
                                    return  '<input class="tgl tgl-skewed" onclick="tenantRole.onSwitchChange(' + row.tenantRoleId +',1 )" id="cb'+row.tenantRoleId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.tenantRoleId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="tenantRole.onSwitchChange(' + row.tenantRoleId +',0 )" id="cb'+row.tenantRoleId+'" type="checkbox" value=' + row.tenantRoleId +'> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.tenantRoleId+'"></label>'
                                }


                            }
                        },
                        {field: 'createdBy', title: '创建人', width: '150', align: 'left'},
                        {field: 'createdTime', title: '创建时间', width: '250', align: 'left'},


                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200', align: 'center',
                            formatter: function (value, row, index) {
                                var a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="查看" onclick="tenantRole.detailRole('
                                    + row.tenantRoleId
                                    + ')"><i class="fa fa-edit">查看</i></a> ';

                                var e = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑" onclick="tenantRole.editTenantRole('
                                    + row.tenantRoleId
                                    + ')"><i class="fa fa-edit">编辑</i></a> ';
                                var d = '<a class="btn btn-warning btn-sm ' + has_delete + '" href="#" title="删除" onclick="tenantRole.remove(\''
                                    + row.tenantRoleId + '\',' + '\'' + row.roleName
                                    + '\')"><i class="fa fa-remove">删除</i></a> ';

                                var b = '<a class="btn btn-warning btn-sm ' + has_delete + '" href="#" title="数据权限" onclick="tenantRole.showModal(\''
                                    + row.tenantRoleId + '\',' + '\'' + row.roleName
                                    + '\')"><i class="fa fa-remove">数据权限</i></a> ';

                                if (row.roleType == '2' || row.roleType == '3') {
                                    return a + d;
;                                }else{
                                    return b + a + e + d;
                                }



                            }
                        }
                    ], onLoadSuccess: function () {

                    }, onPageChange: function () {

                    }
                });
    };

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateRoleStatus",
            data: {
                status: state,
                id: isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
            }
        });
    }



    /**
     * 查询
     */
    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }


    function addTenantRole() {
        location.href = prefix + "/addTenantRole";
    }

    /**
     * 修改
     * @param id
     */
    function editTenantRole(id) {
        location.href = prefix + "/editRole/" + id;
    }

    /**
     * 查看
     * @param id
     */
    function detailRole(id) {
        location.href = prefix + "/checkRole/" + id;
    }

    /**
     * 删除
     * @param id
     */
    function remove(id, name) {
        layer.confirm('确定要删除选中的记录？' + name, {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/remove",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    /**
     * 返回列表
     */
    function goBack() {
        location.href = prefix + "/index";
    }

    var dataAuthList;

    function showModal(tenantRoleId, roleName) {
        $('#exampleModal').modal('show');

        $("#roleNameModel").val(roleName);
        $.ajax({
            url: prefix + "/listDataAuth",
            type: "get",
            data: {
                'tenantRoleId': tenantRoleId
            },
            success: function (data) {
                if (data.status == 200) {
                    dataAuthList = xmSelect.render({
                        el: '#dataAuthList',
                        data: data.data
                    })
                } else {
                    layer.msg("数据加载出错");
                }
            }
        });

        $("#submitForm").unbind("click").bind("click", function () {
            if ("" == dataAuthList.getValue('valueStr')) {
                parent.layer.alert("至少选择一种");
                return;
            }

            $.ajax({
                url: prefix + "/saveDataAuth",
                type: "post",
                data: {
                    'tenantRoleId': tenantRoleId,
                    'dataAuthList': dataAuthList.getValue('valueStr')
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                    }

                }
            })
        })
    }

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                roleName: $('#roleName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addTenantRole: addTenantRole,
        editTenantRole: editTenantRole,
        remove: remove,
        onSwitchChange:onSwitchChange,
        exportList: exportList,
        detailRole: detailRole,
        showModal: showModal
    };
})();

var addRole = (function () {
    var menuIds;

    function init() {
        getMenuTreeData();
        validateRule();
    };

    // $.validator.setDefaults({
    //     submitHandler: function () {
    //         getAllSelectNodes();
    //         save();
    //     }
    // });

    function getAllSelectNodes() {
        var ref = $('#menuTree').jstree(true); // 获得整个树

        menuIds = ref.get_selected(); // 获得所有选中节点的，返回值为数组

        $("#menuTree").find(".jstree-undetermined").each(function (i, element) {
            menuIds.push($(element).closest('.jstree-node').attr("id"));
        });
    }

    function getMenuTreeData() {
        $.ajax({
            type: "GET",
            url: jsctx + "/tenant/menu/tree",
            success: function (menuTree) {
                loadMenuTree(menuTree);
            }
        });
    }

    function loadMenuTree(menuTree) {
        $('#menuTree').jstree({
            'core': {
                'data': menuTree
            },
            "checkbox": {
                "three_state": true,
            },
            "plugins": ["wholerow", "checkbox"]
        });
    }

    function save() {
        $('#menuIds').val(menuIds);
        $.ajax({
            cache: true,
            type: "POST",
            url: jsctx + "/tenant/role/save",
            data: $('#frmAdd').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    tenantRole.goBack();
                } else {
                    parent.layer.msg(data.message);
                }
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmAdd").validate({
            rules: {
                roleName: {
                    required: true
                }
            },
            messages: {
                roleName: {
                    required: icon + "请输入角色名"
                }
            },
            submitHandler: function () {
                getAllSelectNodes();
                save();
            }
        });
    }

    return {
        init: init
    };
})();

var editRole = (function () {
    var menuIds;

    function init() {
        getMenuTreeData();
        validateRule();
    };

    function loadMenuTree(menuTree) {
        $('#menuTree').jstree({
            "plugins": ["wholerow", "checkbox"],
            'core': {
                'data': menuTree
            },
            "checkbox": {
                //"keep_selected_style" : false,
                //"undetermined" : true
                //"three_state" : false,
                //"cascade" : ' up'
            }
        });
        $('#menuTree').jstree('open_all');
    }

    function getAllSelectNodes() {
        var ref = $('#menuTree').jstree(true); // 获得整个树
        menuIds = ref.get_selected(); // 获得所有选中节点的，返回值为数组
        $("#menuTree").find(".jstree-undetermined").each(function (i, element) {
            menuIds.push($(element).closest('.jstree-node').attr("id"));
        });
    }

    function getMenuTreeData() {
        var tenantRoleId = $('#tenantRoleId').val();
        $.ajax({
            type: "GET",
            url: jsctx + "/tenant/menu/tree/" + tenantRoleId,
            success: function (data) {
                loadMenuTree(data);
            }
        });
    }

    function update() {
        $('#menuIds').val(menuIds);
        $.ajax({
            cache: true,
            type: "POST",
            url: jsctx + "/tenant/role/save",
            data: $('#frmEdit').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    tenantRole.goBack();
                } else {
                    parent.layer.msg(data.message);
                }

            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmEdit").validate({
            rules: {
                roleName: {
                    required: true
                }
            },
            messages: {
                roleName: {
                    required: icon + "请输入角色名"
                }
            },
            submitHandler: function () {
                getAllSelectNodes();
                update();
            }
        });
    }

    return {
        init: init
    };
})();